package org.bee.controller;

import org.bee.PageUtil;
import org.bee.ResultTool;
import org.bee.enums.IsDelete;
import org.bee.enums.ResultCode;
import org.bee.exception.ExceptionUtils;
import org.bee.id.UUIDUtils;
import org.bee.input.DepartmentInsertVo;
import org.bee.input.DepartmentSearchVo;
import org.bee.input.DepartmentUpdateVo;
import org.bee.model.AdminUserExample;
import org.bee.model.Department;
import org.bee.model.DepartmentExample;
import org.bee.model.result.Result;
import org.bee.output.DepartmentOut;
import org.bee.output.DepartmentTree;
import org.bee.secuirty.annotation.ApiAuth;
import org.bee.secuirty.context.CurrentUser;
import org.bee.service.AdminUserService;
import org.bee.service.DepartmentService;
import org.bee.transaction.TransUtils;
import org.bee.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 部门表控制器
 */
@RestController
@RequestMapping("/department")
public class DepartmentController {
    Logger logger = LoggerFactory.getLogger(DepartmentController.class);


    private final DepartmentService departmentService;
    private final AdminUserService adminUserService;

    public DepartmentController(DepartmentService departmentService,
                                AdminUserService adminUserService) {
        this.departmentService = departmentService;
        this.adminUserService = adminUserService;
    }
    //    @Resource
//    private AdminApis adminApis;

    /**
     * 新增部门表
     * @param departmentInsertVo 新增参数
     * @return 新增结果
     */
    @PostMapping("insert")
    @ApiAuth(value = "department.insert",description = "部门新增")
    public Result insert(@RequestBody DepartmentInsertVo departmentInsertVo) {
        Result result = ResultTool.success();
        if(departmentInsertVo == null){
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            return result;
        }
        if(departmentInsertVo.getDepartmentName() == null || departmentInsertVo.getDepartmentName().isEmpty()){
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            return result;
        }
        DepartmentExample departmentExample = new DepartmentExample();
        DepartmentExample.Criteria criteria = departmentExample.createCriteria();
        criteria.andDepartmentNameEqualTo(departmentInsertVo.getDepartmentName());
        criteria.andIsDeletedEqualTo(Boolean.valueOf(IsDelete.FALSE.getCode()));
        if (!departmentService.selectByExample(departmentExample).isEmpty()) {
            result = ResultTool.fail(ResultCode.DATA_REPEAT);
            result.setMsg(departmentInsertVo.getDepartmentName()+"已存在");
            return result;
        }
        Transaction trans = null;
        try {
            Department department = new Department();
            BeanUtils.copyProperties(departmentInsertVo, department);
            department.setId(UUIDUtils.simpleUuid());
            department.setCreateUser(CurrentUser.getUser().getUserId());
            department.setCreateTime(new Date());
            department.setIsDeleted(Boolean.valueOf(IsDelete.FALSE.getCode()));
            trans= TransUtils.getTrans();
            trans.begin();
            departmentService.insert(department);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 删除部门表
     * @param id id
     * @return 删除结果
     */
    @DeleteMapping("delete")
    @ApiAuth(value = "department.delete",description = "部门删除")
    public Result delete(@RequestParam("id") String id) {
        Result result = ResultTool.success();
        Transaction trans = null;
        if (id == null|| id.isEmpty()) {
            result = ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
            return result;
        }
        //有下级部门不可删除
        DepartmentExample departmentExample = new DepartmentExample();
        DepartmentExample.Criteria criteria = departmentExample.createCriteria();
        criteria.andPidEqualTo(id);
        criteria.andIsDeletedEqualTo(Boolean.valueOf(IsDelete.FALSE.getCode()));
        if (!departmentService.selectByExample(departmentExample).isEmpty()) {
            result = ResultTool.fail(ResultCode.DATA_IS_USED);
            result.setMsg("有下级部门不可删除");
            return result;
        }
        //部门下有用户不可删除
        AdminUserExample adminUserExample = new AdminUserExample();
        AdminUserExample.Criteria adminUserCriteria = adminUserExample.createCriteria();
        adminUserCriteria.andDepartmentIdEqualTo(id);
        adminUserCriteria.andIsDeletedEqualTo(Boolean.valueOf(IsDelete.FALSE.getCode()));
        if (!adminUserService.selectByExample(adminUserExample).isEmpty()) {
            result = ResultTool.fail(ResultCode.DATA_IS_USED);
            result.setMsg("部门下有用户不可删除");
            return result;
        }
        try {
            trans= TransUtils.getTrans();
            trans.begin();
            departmentService.delete(id,false);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 修改部门表
     * @param departmentUpdateVo 修改参数
     * @return 修改结果
     */
    @PostMapping("update")
    @ApiAuth(value = "department.update",description = "部门修改")
    public Result update(@RequestBody DepartmentUpdateVo departmentUpdateVo) {
        Result result = ResultTool.success();
        Transaction trans = null;
        try {
            Department department = new Department();
            BeanUtils.copyProperties(departmentUpdateVo, department);
            department.setUpdateUser(CurrentUser.getUser().getUserId());
            department.setUpdateTime(new Date());
            trans= TransUtils.getTrans();
            trans.begin();
            departmentService.update(department);
            trans.commit();
        } catch (Exception e) {
            TransUtils.rollback(trans);
            result = ResultTool.fail();
            logger.error(e.getMessage(), ExceptionUtils.getFullStackTrace(e));
            return result;
        }
        return result;
    }

    /**
     * 分页查询查询部门表
     * @param departmentSearchVo 查询参数
     * @return 查询结果
     */
    @PostMapping("pageQuery")
    @ApiAuth(value = "department.pageQuery",description = "部门分页查询")
    public Result select(@RequestBody DepartmentSearchVo departmentSearchVo) {
        Result result = ResultTool.success();
        PageUtil.setPage(departmentSearchVo.getCurrent(),departmentSearchVo.getSize());
        List<Department> select = departmentService.select(departmentSearchVo);
        List<DepartmentOut> selectOut = new ArrayList<>();
        select.forEach(department -> {
            DepartmentOut departmentOut = new DepartmentOut();
            BeanUtils.copyProperties(department, departmentOut);
            selectOut.add(departmentOut);
        });
        result.setPageData(selectOut);
        return result;
    }

    /**
     * 根据id查询部门表
     * @param id id
     * @return 查询结果
     */
    @GetMapping("selectById")
    @ApiAuth(value = "department.selectById",description = "部门根据id查询")
    public Result selectById(String id) {
        Result result = ResultTool.success();
        if(id == null || id.isEmpty()){
            return ResultTool.fail(ResultCode.PARAM_NOT_COMPLETE);
        }
        DepartmentExample departmentExample = new DepartmentExample();
        DepartmentExample.Criteria criteria = departmentExample.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andIsDeletedEqualTo(Boolean.valueOf(IsDelete.FALSE.getCode()));
        List<Department> departments = departmentService.selectByExample(departmentExample);
        if (departments.isEmpty()) {
            return ResultTool.fail(ResultCode.DATA_NULL);
        }
        Department first = departments.getFirst();
        DepartmentOut departmentOut = new DepartmentOut();
        BeanUtils.copyProperties(first, departmentOut);
//        departmentOut.setCreateUser(adminApis.Code("user", first.getCreateUser()));
//        departmentOut.setUpdateUser(adminApis.Code("user", first.getUpdateUser()));
//        departmentOut.setParentName(adminApis.Code("department", first.getPid()));
        result.setData(departmentOut);
        return result;
    }
    /**
     * 部门树
     * @return 查询结果
     */
    @GetMapping("getDepartmentTree")
    @ApiAuth(value = "department.getDepartmentTree",description = "部门树")
    public Result getDepartmentTree() {
        Result result = ResultTool.success();
        List<DepartmentTree> departmentTree = departmentService.getDepartmentTree(null);
        result.setData(departmentTree);
        return result;
    }
}
